package com.web.exiaodao.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Function;
import com.web.exiaodao.business.entity.Institution;
import com.web.exiaodao.business.entity.SysArea;
import com.web.exiaodao.business.repository.InstitutionRepository;
import com.web.exiaodao.business.repository.SysAreaRepository;
import com.web.exiaodao.business.service.InstitutionService;
import com.web.exiaodao.remote.vo.InstitutionVo;
import com.web.exiaodao.remote.vo.SysAreaVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("InstitutionService")
@Transactional(readOnly = false)
public class InstitutionServiceImpl extends BaseService<InstitutionVo> implements InstitutionService {

	private static final Logger LOGGER = Logger.getLogger(InstitutionServiceImpl.class);

    @Autowired
    private SysAreaRepository areaRepository;
	@Autowired
	private InstitutionRepository institutionRepository;
	
	/**
	 * 查询单条Institution信息
	 * //@param tId
	 * @return 返回单个Institution对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<InstitutionVo> findOne(Long modelId) throws BusinessException {
		Institution obj = new Institution();
		if(modelId != 0){
			obj = institutionRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<InstitutionVo> xr = new XaResult<>();
		if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), InstitutionVo.class));
			LOGGER.info("后台----->查询单个实体----->Institution");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的Institution数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象Institution集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<InstitutionVo>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<Institution> page = institutionRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), Institution.class), pageable);
		XaResult<Page<InstitutionVo>> xr = new XaResult<>();
        xr.setObject(new MyPage<>(page, JSON.parseArray(JSON.toJSONString(page.getContent()), InstitutionVo.class)));

        //查询分类信息
        Map<String, SearchFilter> categoryFilters = new HashMap<>();
        categoryFilters.put("status", filters.get("status"));
        List<SysArea> categories = areaRepository.findAll(DynamicSpecifications
                .bySearchFilter(categoryFilters.values(), SysArea.class));
        Map<String,SysArea> categoryMap = com.web.webstart.base.util.CollectionUtils.listToMap(categories != null ? categories.iterator() : null, new Function<SysArea, String>() {
            @Override
            public String apply(SysArea shopCategory) {
                return shopCategory.getId().toString();
            }
        });

        //拼装数据
        List<InstitutionVo> data = xr.getObject().getContent();
        for (int i = 0 ; categoryMap != null && data != null && i < data.size(); ++i) {
            long type =  data.get(i).getSysAreaId();
            SysArea category = categoryMap.get(type+"");
            data.get(i).setSysAreaVo(JSON.parseObject(JSON.toJSONString(category), SysAreaVo.class));
        }

		LOGGER.info("后台----->分页查询实体集合（状态不等于）----->Institution");
		return xr;
	}

	/**
	 * 分页查询状态status的Institution数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象Institution集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<InstitutionVo>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<Institution> page = institutionRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), Institution.class), pageable);
		XaResult<Page<InstitutionVo>> xr = new XaResult<>();
        xr.setObject(new MyPage<>(page, JSON.parseArray(JSON.toJSONString(page.getContent()), InstitutionVo.class)));
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->Institution");
		return xr;
	}

    /**
	 * 保存Institution信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<InstitutionVo> saveOrUpdate(InstitutionVo model) throws BusinessException {
		Institution obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = institutionRepository.findOne(model.getId());
		}else{
			obj = new Institution();
		}
		//使用富文本后出现<p> 标签
		String informations = model.getInstitution_Informations();
		if(informations.length() != 0){
			informations = informations.replace("<p>", "");
			informations = informations.replace("</p>", "");
			model.setInstitution_Informations(informations);
		}
	    obj.setInstitution_Name(XaUtil.isNotEmpty(model.getInstitution_Name()) ? model.getInstitution_Name() : obj.getInstitution_Name());
	    obj.setInstitution_Site(XaUtil.isNotEmpty(model.getInstitution_Site()) ? model.getInstitution_Site() : obj.getInstitution_Site());
	    obj.setInstitution_TelPhone(XaUtil.isNotEmpty(model.getInstitution_TelPhone()) ? model.getInstitution_TelPhone() : obj.getInstitution_TelPhone());
	    obj.setInstitution_Price(XaUtil.isNotEmpty(model.getInstitution_Price()) ? model.getInstitution_Price() : obj.getInstitution_Price());
	    obj.setInstitution_Informations(XaUtil.isNotEmpty(model.getInstitution_Informations()) ? model.getInstitution_Informations() : obj.getInstitution_Informations());
	    obj.setInstitution_VideoUrl(XaUtil.isNotEmpty(model.getInstitution_VideoUrl()) ? model.getInstitution_VideoUrl() : obj.getInstitution_VideoUrl());
	    obj.setInstitution_Area(XaUtil.isNotEmpty(model.getInstitution_Area()) ? model.getInstitution_Area() : obj.getInstitution_Area());
	    obj.setInstitution_type(XaUtil.isNotEmpty(model.getInstitution_type()) ? model.getInstitution_type() : obj.getInstitution_type());
		obj.setInstitutionAddress(XaUtil.isNotEmpty(model.getInstitutionAddress()) ? model.getInstitutionAddress() : obj.getInstitutionAddress());
		obj.setInstitution_pic(XaUtil.isNotEmpty(model.getInstitution_pic()) ? model.getInstitution_pic() : obj.getInstitution_pic());
		obj.setSysAreaId(XaUtil.isNotEmpty(model.getSysAreaId()) ? model.getSysAreaId() : obj.getSysAreaId());
		obj.setClickCont(XaUtil.isNotEmpty(model.getClickCont()) ? model.getClickCont() : obj.getClickCont());
		obj.setSort(XaUtil.isNotEmpty(model.getSort()) ? model.getSort() : obj.getSort());
		obj = institutionRepository.save(obj);
		XaResult<InstitutionVo> xr = new XaResult<InstitutionVo>();
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), InstitutionVo.class));
		LOGGER.info("后台新增或编辑数据成功！");
		return xr;
	}

	/**
	 * 修改Institution状态，可一次修改多条   3删除  -1锁定  1正常
	 * //@param userId
	 * @param modelIds
	 * @param status
	 * @return 返回Institution对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<InstitutionVo> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<InstitutionVo> xr = new XaResult<InstitutionVo>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				Institution obj = institutionRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = institutionRepository.save(obj);
				}
			}
		}
		LOGGER.info("批量修改数据状态成功！");
		return xr;
	}
	
}
